package com.example.cm_design

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat

/**
 * 自定义音乐进度条，支持拖动和进度显示
 */
class MusicProgressBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 进度相关
    private var progress = 0f
    private var max = 100f
    
    // 画笔
    private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val thumbPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    
    // 尺寸
    private val trackHeight = context.resources.getDimensionPixelSize(R.dimen.track_height)
    private val thumbRadius = context.resources.getDimensionPixelSize(R.dimen.thumb_radius)
    private val trackRectF = RectF()
    
    // 颜色
    private val trackBackgroundColor = ContextCompat.getColor(context, R.color.track_background)
    private val trackProgressColor = ContextCompat.getColor(context, R.color.track_progress)
    private val thumbColor = ContextCompat.getColor(context, R.color.thumb_color)
    
    // 拖动相关
    private var isDragging = false
    private var listener: OnProgressChangeListener? = null
    
    init {
        // 初始化画笔
        backgroundPaint.color = trackBackgroundColor
        backgroundPaint.style = Paint.Style.FILL
        
        progressPaint.color = trackProgressColor
        progressPaint.style = Paint.Style.FILL
        
        thumbPaint.color = thumbColor
        thumbPaint.style = Paint.Style.FILL
    }
    
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val minHeight = thumbRadius * 2 + paddingTop + paddingBottom
        val height = resolveSize(minHeight, heightMeasureSpec)
        val width = resolveSize(suggestedMinimumWidth, widthMeasureSpec)
        setMeasuredDimension(width, height)
    }
    
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        
        // 计算track绘制区域
        val left = paddingLeft.toFloat() + thumbRadius
        val right = width - paddingRight.toFloat() - thumbRadius
        val top = (height - trackHeight) / 2f
        val bottom = top + trackHeight
        
        // 绘制背景
        trackRectF.set(left, top, right, bottom)
        canvas.drawRoundRect(trackRectF, trackHeight / 2f, trackHeight / 2f, backgroundPaint)
        
        // 绘制进度
        val progressWidth = (right - left) * (progress / max)
        trackRectF.set(left, top, left + progressWidth, bottom)
        canvas.drawRoundRect(trackRectF, trackHeight / 2f, trackHeight / 2f, progressPaint)
        
        // 绘制拖动点
        val thumbCenterX = left + progressWidth
        val thumbCenterY = height / 2f
        canvas.drawCircle(thumbCenterX, thumbCenterY, thumbRadius.toFloat(), thumbPaint)
    }
    
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event ?: return super.onTouchEvent(event)
        
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                // 检查是否点击在thumb上
                val thumbX = paddingLeft + thumbRadius + (width - paddingLeft - paddingRight - 2 * thumbRadius) * (progress / max)
                val thumbY = height / 2f
                
                val distance = Math.sqrt(Math.pow((event.x - thumbX).toDouble(), 2.0) + 
                                        Math.pow((event.y - thumbY).toDouble(), 2.0))
                
                isDragging = distance <= thumbRadius * 2
                return isDragging
            }
            
            MotionEvent.ACTION_MOVE -> {
                if (isDragging) {
                    updateProgressFromX(event.x)
                    return true
                }
            }
            
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                if (isDragging) {
                    updateProgressFromX(event.x)
                    listener?.onProgressChanged(progress, true)
                    isDragging = false
                    return true
                }
            }
        }
        
        return super.onTouchEvent(event)
    }
    
    private fun updateProgressFromX(x: Float) {
        val available = width - paddingLeft - paddingRight - 2 * thumbRadius
        val relativeX = x - paddingLeft - thumbRadius
        
        progress = when {
            relativeX <= 0 -> 0f
            relativeX >= available -> max
            else -> (relativeX / available) * max
        }
        
        listener?.onProgressChanged(progress, false)
        invalidate()
    }
    
    /**
     * 设置进度
     */
    fun setProgress(value: Float) {
        progress = value.coerceIn(0f, max)
        invalidate()
    }
    
    /**
     * 设置最大值
     */
    fun setMax(value: Float) {
        max = value
        invalidate()
    }
    
    /**
     * 设置进度变化监听器
     */
    fun setOnProgressChangeListener(listener: OnProgressChangeListener) {
        this.listener = listener
    }
    
    /**
     * 进度变化监听接口
     */
    interface OnProgressChangeListener {
        /**
         * 进度变化回调
         * @param progress 当前进度
         * @param fromUser 是否来自用户操作
         */
        fun onProgressChanged(progress: Float, fromUser: Boolean)
    }
} 